package com.jakewharton.rxbinding4.component;

import com.jakewharton.rxbinding4.InitialValueObservable;

import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.openharmony.MainThreadDisposable;
import ohos.agp.components.PageSlider;

final class ViewPagerPageChosenObservable extends InitialValueObservable<Integer> {
    private final PageSlider view;

    ViewPagerPageChosenObservable(PageSlider view) {
        this.view = view;
    }

    @Override
    protected void subscribeListener(Observer<? super Integer> observer) {
        Listener listener = new Listener(view, observer);
        observer.onSubscribe(listener);
        view.addPageChangedListener(listener);
    }

    @Override
    protected Integer getInitialValue() {
        return view.getCurrentPage();
    }

    static final class Listener extends MainThreadDisposable implements PageSlider.PageChangedListener {
        private final PageSlider view;
        private final Observer<? super Integer> observer;

        Listener(PageSlider view, Observer<? super Integer> observer) {
            this.view = view;
            this.observer = observer;
        }

        @Override
        protected void onDispose() {
            view.removePageChangedListener(this);
        }

        @Override
        public void onPageSliding(int i, float v, int i1) {}

        @Override
        public void onPageSlideStateChanged(int i) {}

        @Override
        public void onPageChosen(int position) {
            if (!isDisposed()) {
                observer.onNext(position);
            }
        }
    }
}
